package com.jxb.permissions;

import android.app.Activity;

import com.blankj.utilcode.util.ToastUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;

import java.util.List;

/**
 * @author jinxb
 * date     : 2021/8/12
 * desc     :
 */
public class JxbPermissions {

    public static void requestPermissions(Activity activity, String[] permissionNames, String[] permissions,
                                          RequestSuccessListener successListener) {
        requestPermissions(activity, permissionNames, permissions, successListener, null);
    }


    public static void requestPermissions(Activity activity, String[] permissionNames, String[] permissions,
                                          RequestSuccessListener successListener, RequestErrorListener errorListener) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < permissionNames.length; i++) {
            sb.append(permissionNames[i]);
            if (i < permissionNames.length - 1) {
                sb.append(",");
            }
        }
        String permissionInfo = sb.toString();

        XXPermissions.with(activity)
                // 申请多个权限
                .permission(permissions)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            if (successListener != null) {
                                successListener.requestSuccess();
                            }
                        } else {
                            error(permissionInfo, errorListener);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtils.showShort("被永久拒绝授权，请手动授予" + permissionInfo + "权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(activity, permissions);
                        } else {
                            error(permissionInfo, errorListener);
                        }
                    }
                });
    }

    private static void error(String permissionInfo, RequestErrorListener errorListener) {
        ToastUtils.showShort("请开启" + permissionInfo + "权限");
        if (errorListener != null) {
            errorListener.requestError();
        }
    }

    public interface RequestSuccessListener {
        void requestSuccess();
    }

    public interface RequestErrorListener {
        void requestError();
    }
}
